module.exports = function ($scope, $modalInstance, $resource, $modal, item, flag, toaster){

    //加载全部销售品列表
	$scope.loadSaleType = function (){
		$resource('/api/as/sc/dict/dictbytypelist', {}, {}).save({'type': 'sale_category'}, function (res) {
            if (res.errcode === 0) {
                $scope.sale_type_list = res.data;
                if(!flag){
                    var sale_type = ',' + item.channel_sale_type + ',';
                    angular.forEach($scope.sale_type_list, function(sale){
                        sale.state = sale_type.indexOf(',' + sale.value + ',') != -1;
                    });
                }
            } else {
                toaster.error({title: '', body: res.errmsg});
            }
        });
    }

    init();
    function init(){
        $scope.channel = flag ? {'flag': true} : angular.copy(item);
        $scope.loadSaleType();
    }

    //保存
	$scope.save = function (){
        var save_list = [];
        angular.forEach($scope.sale_type_list, function(item){
            if(item.state){
                save_list.push(item.value);
            }
        });
        var para = {
            'channel_list_name': $scope.channel.channel_list_name,
            'channel_sale_type': save_list.toString(),
            'channel_list_code': flag ? $scope.channel.channel_code : item.channel_list_code
        }
        var url = flag ? '/api/as/tc/salechannel/save' : '/api/as/tc/salechannel/update';
        $resource(url, {}, {}).save(para, function(res){
        	if(res.errcode === 0){
                toaster.success({title: '', body: '保存渠道成功'});
        		$modalInstance.close();
        	}else{
                toaster.error({title: '', body: res.errmsg});
        	}
        });
    }

    //全选or全不选
    $scope.selAll = function(){
        angular.forEach($scope.sale_type_list, function(item){
            item.state = $scope.all;
        });
    }

    //取消
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    }

};